package com.jiangdg.usbcamera.view;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Surface;
import android.view.View;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.Toast;
import com.jiangdg.usbcamera.R;
import com.jiangdg.usbcamera.UVCCameraHelper;
import com.jiangdg.usbcamera.utils.FileUtils;
import com.serenegiant.usb.CameraDialog;
import com.serenegiant.usb.USBMonitor;
import com.serenegiant.usb.common.AbstractUVCCameraHandler;
import com.serenegiant.usb.encoder.RecordParams;
import com.serenegiant.usb.widget.CameraViewInterface;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
 * UVCCamera use demo
 * <p>
 * Created by jiangdongguo on 2017/9/30.
 */

public class USBCameraActivity extends AppCompatActivity implements CameraDialog.CameraDialogParent, CameraViewInterface.Callback {
    private static final String TAG = "Debug";
    @BindView(R.id.camera_view)
    public View mTextureView;
    @BindView(R.id.toolbar)
    public Toolbar mToolbar;
    @BindView(R.id.seekbar_brightness)
    public SeekBar mSeekBrightness;
    @BindView(R.id.seekbar_contrast)
    public SeekBar mSeekContrast;
    @BindView(R.id.switch_rec_voice)
    public Switch mSwitchVoice;

    private UVCCameraHelper mCameraHelper;
    private CameraViewInterface mUVCCameraView;

    private boolean isRequest;
    private boolean isPreview;//摄像头调用成功

    private Timer timer;
    boolean isRecordVideo = false;//是否在录制

    private UVCCameraHelper.OnMyDevConnectListener listener = new UVCCameraHelper.OnMyDevConnectListener() {
        @Override
        public void onAttachDev(UsbDevice device) {
            showShortMsg("listener");
            Log.d("Context","listener:");
//            try {
//                thread.stop();
//            }
//            catch (Exception e){
//                Log.d("Context","thread1:"+e);
//            }
//            thread.start();

            if (mCameraHelper == null || mCameraHelper.getUsbDeviceCount() == 0) {
                showShortMsg("check no usb camera");
                return;
            }
            // request open permission
            if (!isRequest) {
                isRequest = true;
                if (mCameraHelper != null) {
                    mCameraHelper.requestPermission(0);
                }
            }
        }

        @Override
        public void onDettachDev(UsbDevice device) {
            // close camera
            if (isRequest) {
                isRequest = false;
                mCameraHelper.closeCamera();
                showShortMsg(device.getDeviceName() + " is out");
            }
        }

        @Override
        public void onConnectDev(UsbDevice device, boolean isConnected) {
            if (!isConnected) {
                showShortMsg("fail to connect,please check resolution params");
                isPreview = false;

//                try {
//                    thread.stop();
//                }
//                catch (Exception e){
//                    Log.d("Context","thread1:"+e);
//                }
//                thread.start();
            } else {
                isPreview = true;
                showShortMsg("connecting");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        Looper.prepare();
                        if(mCameraHelper != null && mCameraHelper.isCameraOpened()) {
                            mSeekBrightness.setProgress(mCameraHelper.getModelValue(UVCCameraHelper.MODE_BRIGHTNESS));
                            mSeekContrast.setProgress(mCameraHelper.getModelValue(UVCCameraHelper.MODE_CONTRAST));
                        }
                        Looper.loop();
                    }
                }).start();
            }
        }

        @Override
        public void onDisConnectDev(UsbDevice device) {
            showShortMsg("disconnecting");
        }
    };


    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("myReceiver")){
                Log.d("Context","广播");
                if(isPreview){

                }
                else{

                }
            }
        }
    };


    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            try{
                thread.stop();
            }
            catch (Exception e){
                Log.d("Context","thread2:"+e);
            }

            Log.d("Context","handler:"+isPreview);

            if (isPreview){
                try {
                    Thread.sleep(3000);
                }
                catch (Exception e){
                    Log.d("Context","timeThread2 error:"+e);
                }
                timerSchedule(1);
            }
            else{
                mCameraHelper.unregisterUSB();
                try {
                    Thread.sleep(5*1000);
                    mCameraHelper.registerUSB();
                }
                catch (Exception e){
                    Log.d("Context","error:"+e);
                }

                thread.start();

            }

        }
    };


    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(10*1000);
            }
            catch (Exception e){
                Log.d("Context","error:"+e);
            }
            Message message = new Message();
            message.what=0;
            handler.sendMessage(message);
        }
    });

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_usbcamera);
        ButterKnife.bind(this);

        // step.1 initialize UVCCameraHelper
        mUVCCameraView = (CameraViewInterface) mTextureView;
        mUVCCameraView.setCallback(this);
        mCameraHelper = UVCCameraHelper.getInstance();
        mCameraHelper.setDefaultPreviewSize(320,240);
        mCameraHelper.initUSBMonitor(this, mUVCCameraView, listener);

        // 注册广播监听
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("myReceiver");
        registerReceiver(receiver, intentFilter);

        timer = new Timer();

        try {
            thread.stop();
        }
        catch (Exception e){
            Log.d("Context","thread1:"+e);
        }
        thread.start();

    }


    //time秒后执行 RemindTask（）
    private void timerSchedule(int time){
        timer.schedule(new RemindTask(),1000*time);
    }

    //
    class RemindTask extends TimerTask {
        public void run() {
            if (isRecordVideo){
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        StopVideo();
                    }
                });
            }
            try{
                Thread.sleep(3000);
            }
            catch (Exception e){
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    timerSchedule(60*60);//60分钟
                    RecordVideo(getPath());
                }
            });
        }
    }

    //根据当前时间创建文件，并返回新建文件夹路径
    private String getPath(){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        String data = df.format(calendar.getTime());

        String path = Environment.getExternalStorageDirectory().getPath() + "/Mvideo";

        File myDir = new File(path);
        if (!myDir.exists()) {
            if (!myDir.mkdirs()) {
                return "";
            }
        }
        File video_file = new File(myDir, data);
        return video_file.getAbsolutePath();
    }

    private void RecordVideo(String filePath){
        if (mCameraHelper == null || !mCameraHelper.isCameraOpened() || filePath.length()<5) {
            showShortMsg("sorry,camera open failed");
            return ;
        }
        //开始录制
        if (!mCameraHelper.isRecording()) {
            isRecordVideo = true;
            RecordParams params = new RecordParams();
            params.setRecordPath(filePath);
            params.setRecordDuration(0);                        // 设置为0，不分割保存
            params.setVoiceClose(mSwitchVoice.isChecked());    // is close voice
            mCameraHelper.startRecording(params, new AbstractUVCCameraHandler.OnEncodeResultListener() {
                @Override
                public void onEncodeResult(byte[] data, int offset, int length, long timestamp, int type) {
                    if (type == 1) {

                    }
                    if(type == 0) {

                    }
                }
                @Override
                public void onRecordResult(String videoPath) {
                    Log.i(TAG,"videoPath = "+videoPath);
                }
            });
            showShortMsg("start record...");
            mSwitchVoice.setEnabled(false);
        }
    }

    //停止录制
    private void StopVideo(){
        try {
            isRecordVideo = false;
            mCameraHelper.stopRecording();
            showShortMsg("stop record...");
            mSwitchVoice.setEnabled(true);
        }
        catch (Exception e){
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mCameraHelper != null) {
            mCameraHelper.registerUSB();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
//        if (mCameraHelper != null) {
//            mCameraHelper.unregisterUSB();
//        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        StopVideo();
        FileUtils.releaseFile();
        // step.4 release uvc camera resources
        unregisterReceiver(receiver);
        if (mCameraHelper != null) {
            mCameraHelper.release();
        }
    }

    private void showShortMsg(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public USBMonitor getUSBMonitor() {
        return mCameraHelper.getUSBMonitor();
    }

    @Override
    public void onDialogResult(boolean canceled) {
        if (canceled) {
            showShortMsg("取消操作");
        }
    }

    @Override
    public void onSurfaceCreated(CameraViewInterface view, Surface surface) {
        if (!isPreview && mCameraHelper.isCameraOpened()) {
            mCameraHelper.startPreview(mUVCCameraView);
            isPreview = true;
        }
    }

    @Override
    public void onSurfaceChanged(CameraViewInterface view, Surface surface, int width, int height) {
    }

    @Override
    public void onSurfaceDestroy(CameraViewInterface view, Surface surface) {
        if (isPreview && mCameraHelper.isCameraOpened()) {
            mCameraHelper.stopPreview();
            isPreview = false;
        }
    }
}
